<template>
  <div class="listing-details-page">
    <van-nav-bar title="商品上架"  fixed safe-area-inset-top />

    <div class="content">
      <!-- 数据加载提示 -->
      <div v-if="!receivedItem" class="loading-tip">
        <van-loading type="spinner" size="24px" />
        <span>正在加载商品信息...</span>
      </div>
      
      <!-- 商品信息卡片 -->
      <div v-if="receivedItem" class="card product-card decorated">
        <div class="product-title">商品信息</div>
        <div class="product-code">{{ receivedItem['689bf502ad18b78d3f356dbb'] || '69码' }}</div>
        <div class="product-sub">{{ receivedItem['689bf4a6ad18b78d3f356d9a'] || '商品名称' }}</div>
      </div>

      <!-- 库位选择 -->
      <div v-if="receivedItem" class="action-row">
        <div class="action-box input-box">
          <i class="i-slot">库</i>
          <input 
            v-model="locationCode" 
            type="text" 
            class="location-input" 
            placeholder="输入上架库位编码"
          />
        </div>
      </div>
      
      <!-- 统计信息 -->
      <div v-if="receivedItem" class="card info-list">
        <!-- 选择商品日期 -->
        <div class="info-item date-selection-item">
          <span class="label">选择商品日期</span>
          <div class="value-with-date" @click="onSelectDateClick">
            <span :class="{ 'selected-date': selectedDate }">
              {{ selectedDate || '请选择日期' }}
            </span>
            <i class="date-arrow">▼</i>
          </div>
        </div>
        <div class="divider"></div>
        
        <div class="info-item">
          <span class="label">应上架数</span>
          <span class="value">{{ EPQuantity|| '— —' }}</span>
        </div>
        <div class="divider"></div>
        <div class="info-item">
          <span class="label">剩余上架数</span>
          <span class="value">{{ receivedItem['689bf876ad18b78d3f356ebe'] || '— —' }}</span>
        </div>
        <div class="divider"></div>
        <div class="info-item">
          <span class="label">上架数</span>
          <div class="value-with-input">
            <input
              v-model="actualQuantity"
              type="number"
              inputmode="numeric"
              pattern="[0-9]*"
              step="1"
              class="quantity-input"
              placeholder="输入上架数量"
              min="0"
              :max="Number(receivedItem['689bf876ad18b78d3f356ebe'] || 0)"
              autocomplete="off"
            />
          </div>
        </div>
  
      </div>

      
      <!-- 操作按钮 -->
      <div v-if="receivedItem" class="action-box ghost h50" @click="onConfirmClick">
          <span @click="onConfirmClick">确认上架</span>
        </div>
    </div>
    
    <!-- 移动端日期选择器 -->
    <van-action-sheet 
      v-model:show="showDatePicker" 
      title="选择商品日期"
      :actions="dateOptions.map((date, index) => ({
        name: date,
        value: date,
        index: index
      }))"
      @select="onDateSelect"
      cancel-text="取消"
      close-on-click-action
      :round="false"
      safe-area-inset-bottom
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showDialog } from 'vant'
import axios from 'axios'
import { api, utils } from "mdye";
import { config } from 'mdye';




// 显示确认对话框的封装函数
const showConfirmDialog = (options) => {
  return new Promise((resolve, reject) => {
    showDialog({
      title: options.title || '确认操作',
      message: options.message || '确定要执行此操作吗？',
      confirmButtonText: options.confirmButtonText || '确认',
      confirmButtonColor: options.confirmButtonColor || '#667eea',
      cancelButtonText: options.cancelButtonText || '取消',
      showCancelButton: true
    })
      .then(() => {
        // 用户点击确认按钮
        resolve(true);
      })
      .catch(() => {
        // 用户点击取消按钮，不抛出异常，而是返回false
        resolve(false);
      });
  });
};

const router = useRouter()
const locationCode = ref('')
// 日期选择相关
const selectedDate = ref('')
const dateOptions = ref([])
const showDatePicker = ref(false)
const dateRecords = ref([]) // 存储完整的日期记录数据

// 接收传递过来的数据
const receivedItem = ref(null)

const EPQuantity = ref(0) // 应上架数

const oldNumber = ref(0) // 应上架数

const listNumRef = ref(0) // 已上架数

// 实际上架数量输入
const actualQuantity = ref('')
const dateRowid = ref()

const getAssociatedData = async (rowId, controlId) => {
    const res = await api.getRowRelationRows({
      controlId: controlId,
      rowId: rowId,
      worksheetId: '6864a7614e2949f4119907b9',
      keywords: '',
    });
    console.log('res:', res);
    const arr = res.data.map(item => {
      return item.rowid
    })
    return arr
  }


  const getDateInfo = async (dateRowidArr) => {
  const arr = await Promise.all(
    dateRowidArr.map(async (rowId) => {
      const dateInfo = await api.getRowDetail({
        appId: config.appId,
        worksheetId: '6879b0698371cd243659a3d6',
        viewId: '',
        rowId: rowId, // 注意这里要用动态 rowId
        getTemplate: false,
      });
      return JSON.parse(dateInfo.rowData); // 这里就是你想要的「对象」
    })
  );

  console.log('getDateInfo:');
  
  console.log(arr);
  

  const newArr = arr.map(item => {
    return {
      date: item['6879b14b8371cd243659a496'],
      rowid: item['rowid'],
      number: item['68a03897d166eff684062430'], //应上架数
      listNum: item['688c8c7682289045da81806f'], //已上架数,
      oldNumber: item['6879b14b8371cd243659a495'], //应上架数
    }
  })
  return newArr;
};

const getStateCode = async(stateCode ) => {
  const url = 'https://www.dachen.vip/api/v2/open/worksheet/getFilterRows'
  const res = await axios.post(url, {
  "appKey": "abe3914d3de38c45",
  "sign": "ZWE5ZDY4MmViOWQwNjNkMzg2NWRiMTJlZGZjMjE5ZDZlM2NmNzFmZDI4ZDZhNTY1ODQzNDExMTVkNWE1N2RiZQ==",
  "worksheetId": "686359fb87058ae1c65da317",
  "viewId": "",
  "notGetTotal": true,
   "filters":[
        {
"controlId":"686650f557603df8e65d26a9",
"dataType":2,
"spliceType":1,
"filterType":2,
"value":stateCode
}
   ]
});
 const exists = !!(res?.data?.data?.rows?.length);
 return exists
}

// 选择日期
const onSelectDateClick = async () => {
  try {
    
    const res = await api.getRowRelationRows({
      controlId: '689da383c82bfc2f84b3b629',
      rowId: receivedItem.value.rowid,
      worksheetId: '6864a7614e2949f4119907b9',
      keywords: '',
    });

    const dateRowidArr = res.data.map(item => {
      return item['rowid']
    })

    console.log('获取到的日期数据:', dateRowidArr);


    const arr =  await getDateInfo(dateRowidArr)
    
    // 过滤掉listNum大于等于number的日期
    const filteredArr = arr.filter(item => {
      const listNum = Number(item.listNum || 0); // 已上架数
      const number = Number(item.oldNumber || 0); // 应上架数

      console.log('过滤日期' + listNum, number);
      

      return listNum < number; // 只保留listNum小于number的日期
    });
    
    console.log('过滤前日期数量:', arr.length, '过滤后日期数量:', filteredArr.length);
    
    // 存储完整的日期记录数据，用于后续获取rowid
    dateRecords.value = filteredArr;
    
    const dateArr = filteredArr.map(item => {
      return item['date']
    })
    console.log('过滤后的日期数组:', dateArr);
     console.log('filteredArr:', filteredArr[0]);
    
    // 更新日期选项
    dateOptions.value = dateArr;
    
    if (dateOptions.value.length  === 0) {
      showToast({
        type: 'warning',
        message: arr.length > 0 ? '所有日期已达到上架上限，无可选日期' : '没有可选的日期',
        duration: 2000
      });
      return;
    }
    
    // 如果只有一个日期选项，直接选择
    if (dateOptions.value.length === 1) {
      console.log('只有一个日期选项');
      
      const singleDateItem = filteredArr[0];
      // 确认该日期项的listNum小于number
      const listNum = Number(singleDateItem.listNum || 0); // 已上架数
      const number = Number(singleDateItem.oldNumber || 0); // 不变的应上架数
      console.log(JSON.stringify(singleDateItem));
      console.log(listNum);
      console.log(number);
      
      
      
      if (Number(listNum) <= Number(number)) {
        selectedDate.value = singleDateItem.date;
        listNumRef.value = singleDateItem.listNum;
        dateRowid.value = singleDateItem.rowid;
        EPQuantity.value = singleDateItem.number;
        oldNumber.value = singleDateItem.oldNumber;
        console.log('singleDateItem赋值完成');
        
      }
      
      return;
    }
  
    
    // 显示移动端友好的日期选择器
    showDatePicker.value = true;
    
  } catch (error) {
    console.error('选择日期失败:', error);
    showToast({
      type: 'fail',
      message: '选择日期失败，请检查数据格式',
      duration: 2000
    });
  }
}

// 处理日期选择
const onDateSelect = (action) => {
  selectedDate.value = action.name;
  
  // 根据选择的日期找到对应的rowid
  const matchedRecord = dateRecords.value.find(item => item['date'] === action.name);
  
  if (matchedRecord && matchedRecord.rowid) {
    dateRowid.value = matchedRecord.rowid;
    EPQuantity.value = matchedRecord.number; 
    listNumRef.value = matchedRecord.listNum;
    oldNumber.value = matchedRecord.oldNumber;
  } else {
    console.error('未找到选择日期对应的记录');
  }
  
  showDatePicker.value = false;

}

const onConfirmClick = async () => {
  // 检查必填项
  if (!locationCode.value || locationCode.value.trim() === '') {
    showToast({
      type: 'fail',
      message: '请输入上架库位编码'
    })
    return
  }
  if (locationCode.value == 'SH-01-01-01-01' || locationCode.value == 'CP-01-01-01-01' || locationCode.value == 'JH-01-01-01-01' || locationCode.value == 'CY-01-01-01-01') {
    showToast({
      type: 'fail',
      message: '不能上架到该库位'
    })
    return
  }

  const exists = await getStateCode(locationCode.value)
  if (!exists) {
    showToast({
      type: 'fail',
      message: '该库位不存在'
    })
    return 
  }

  if (!selectedDate.value) {
    showToast({
      type: 'fail',
      message: '请选择商品日期'
    })
    return
  }

  if (!dateRowid.value) {
    showToast({
      type: 'fail',
      message: '日期选择异常，请重新选择'
    })
    return
  }

  if (!actualQuantity.value) {
    showToast({
      type: 'fail',
      message: '请输入上架数量'
    })
    return
  }

  // 获取剩余上架数
  const remainingQuantity = Number(receivedItem.value['689bf876ad18b78d3f356ebe'] || 0);
  // 检查上架数是否大于剩余上架数:1 11
  // console.log('检查上架数是否大于剩余上架数:' + actualQuantity.value, remainingQuantity);
  // // 检查上架数是否大于剩余上架数
  // if (Number(actualQuantity.value) > remainingQuantity) {
    
  //   showToast({
  //     type: 'fail',
  //     message: '上架数量不能大于剩余上架数'
  //   })
  //   return
  // }
  console.log('检查上架数是否大于剩余上架数:' + actualQuantity.value, listNumRef.value,oldNumber.value);
  // 检查上架数是否大于应上架数
  if (Number(actualQuantity.value) + Number(listNumRef.value) > oldNumber.value) {
    showToast({
      type: 'fail',
      message: '上架数量不能大于应上架数'
    })
    return
  }

  try {
    console.log('开始上架流程，商品:', receivedItem.value);
    
    // 确保receivedItem是有效对象
    if (!receivedItem.value || !receivedItem.value.rowid) {
      console.error('无效的商品数据:', receivedItem.value);
      showToast({
        type: 'fail',
        message: '上架失败：无效的数据'
      });
      return;
    }
    
    console.log('显示确认对话框...');
    const confirmed = await showConfirmDialog({
      title: '确认上架',
      message: `确定要将 ${actualQuantity.value} 件商品上架到当前库位吗？\n剩余上架数: ${receivedItem.value['689bf876ad18b78d3f356ebe'] || 0}`,
      confirmButtonText: '确认上架',
      cancelButtonText: '取消'
    });
    
    // 如果用户取消了操作，直接返回
    if (!confirmed) {
      console.log('用户取消了上架操作');
      return;
    }
    
    console.log('用户确认上架，商品ID:', receivedItem.value.rowid);
    console.log('选择的日期:', selectedDate.value);
    console.log('日期记录ID:', dateRowid.value);
    
    // 显示加载提示，但不存储引用，避免使用clear方法
    showToast({
      type: 'loading',
      message: '正在处理上架请求...',
      duration: 0,
      forbidClick: true
    });

    // 获取关联数据
    const arr = await getAssociatedData(receivedItem.value.rowid, '687700e75d31544df2c58ad4')
    const batchIdArr = await getAssociatedData(receivedItem.value.rowid, '686b99a23f0e1b398c1cd3be')

    const unloadUrl = 'https://www.dachen.vip/api/workflow/hooks/Njg5ZDNlY2JlMTRiMGQ3YmRjMWE3MmY5';
    const data = {
      detailsArr: arr,
      batchIdArr: batchIdArr,
      dateRowid: dateRowid.value, // 添加日期记录的rowid
      code: locationCode.value,
      number: actualQuantity.value
    }
    
    // 调用装卸服务API
    await axios.post(unloadUrl, data, {
      headers: { 'Content-Type': 'application/json' }
    });
    
    console.log('上架成功');
    
    // 不使用clear方法，而是直接显示新的Toast覆盖旧的
    showToast({
      type: 'success',
      message: '上架成功！',
      duration: 1500
    });
    
    // 延迟后返回上一页
    setTimeout(() => {
      router.back();
    }, 1800);
    
  } catch (error) {
    console.error('上架处理过程中发生错误:', error);
    
    // 不使用clear方法，而是直接显示新的Toast覆盖旧的
    if (error.response) {
      // API调用失败
      console.error('上架失败:', error.response.data);
      showToast({
        type: 'fail',
        message: '上架失败，请稍后重试',
        duration: 3000
      });
    } else {
      // 其他错误
      console.error('上架失败:', error);
      showToast({
        type: 'fail',
        message: '上架失败：' + (error.message || '未知错误'),
        duration: 3000
      });
    }
  }
}



const getInfo = async () => {
  console.log('config');
  console.log(config);
  
  console.log(config.currentAccount.mobilePhone);

  await axios.post('https://www.dachen.vip/api/workflow/hooks/Njg5ZWZkYWFhODczNjE0ZDQyODc2NTk3', {
    rowid: receivedItem.value['rowid'],
    accountId: config.currentAccount.mobilePhone
  })
  
}



onMounted(() => {
  // 从路由state中获取传递的数据
  try {
    // 使用nextTick延迟数据加载，避免初始化时的强制重排
    nextTick(() => {
      const receipt = window.history.state?.usr?.receipt || window.history.state?.receipt
      if (receipt) {
        receivedItem.value = receipt
        console.log('接收到的出货单数据:', receivedItem.value)

        getInfo()

      } else {
        console.warn('未获取到 receipt，可能是直接刷新或外部链接进入。')
      }
    })
    
  } catch (error) {
    console.error('获取传递的数据失败:', error)
  }
})
</script>

<style scoped>
.listing-details-page {
  background: #f8f9fa;
  min-height: 100vh;
  padding: 16px;
  color: #000000;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  /* 添加硬件加速，减少重排 */
  transform: translateZ(0);
  will-change: transform;
}

.content {
  padding: 64px 14px 24px;
}

.loading-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #6b7280;
  font-size: 14px;
  gap: 12px;
}

/* 通用卡片样式（与ListingPage.vue保持一致） */
.card {
  background: white;
  border-radius: 24px;
  padding: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.card::before {
  content: '';
  position: absolute;
  top: 0; left: 0; right: 0;
  height: 8px;
  background: #f8b300;
}

.card:hover {
  transform: translateY(-4px);
  box-shadow: 0 16px 48px rgba(0, 0, 0, 0.2);
}

.product-card { 
  padding: 24px; 
  text-align: center; 
  position: relative; 
  overflow: hidden; 
}

.product-title { 
  color: #4a5568; 
  font-size: 14px; 
  font-weight: 600;
  margin-bottom: 8px;
}
.product-code { 
  font-size: 24px; 
  font-weight: 700; 
  color: #2d3748; 
  margin: 12px 0; 
  letter-spacing: 1px; 
}
.product-sub { 
  color: #718096; 
  font-size: 13px; 
  line-height: 1.4;
}

.action-row { 
  display: flex; 
  gap: 12px; 
  margin-top: 16px; 
}

.action-box {
  flex: 1; 
  height: 48px; 
  border-radius: 16px; 
  border: 1px solid rgba(0, 0, 0, 0.06);
  background: white; 
  color: #2d3748; 
  display: flex; 
  align-items: center; 
  justify-content: center;
  font-size: 14px; 
  font-weight: 600;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08); 
  gap: 8px; 
  cursor: pointer;
  transition: all 0.2s ease;
}

.action-box:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
}

.action-box.ghost { 
  background: #f8fafc; 
  color: #4a5568; 
}

.action-box.input-box {
  padding: 0 12px;
}

.location-input {
  flex: 1;
  height: 36px;
  border: none;
  background: transparent;
  font-size: 14px;
  font-weight: 500;
  color: #2d3748;
  outline: none;
  text-align: center;
}

.location-input::placeholder {
  color: #a0aec0;
  font-weight: 400;
}

.i-slot { 
  display: inline-flex; 
  align-items: center; 
  justify-content: center; 
  width: 24px; 
  height: 24px; 
  border-radius: 50%; 
  background: #fff3cd; 
  color: #f8b300; 
  font-size: 12px; 
  font-style: normal; 
  font-weight: 700; 
}

.info-list { 
  margin-top: 16px; 
  padding: 8px 12px; 
}

.info-item { 
  display: flex; 
  align-items: center; 
  padding: 12px 6px; 
}

.label { 
  width: 120px; 
  color: #718096; 
  font-size: 13px; 
  font-weight: 500;
}

.value { 
  color: #2d3748; 
  font-weight: 700; 
  font-size: 15px; 
}

.value-with-input {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity-input {
  width: 200px;
  height: 40px;
  text-align: center;
  border: 2px solid #e2e8f0;
  border-radius: 20px;
  padding: 6px 16px;
  font-size: 16px;
  font-weight: 600;
  color: #2d3748;
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;
  outline: none;
  -webkit-appearance: none;
  -moz-appearance: textfield;
  /* 添加硬件加速，减少重排 */
  transform: translateZ(0);
  will-change: transform;
}

.quantity-input:focus {
  border-color: #f8b300;
  box-shadow: 0 0 0 3px rgba(248, 179, 0, 0.1);
  background-color: #fff9e6;
}

.quantity-input:active {
  transform: scale(0.98);
}

.quantity-input::placeholder {
  color: #a0aec0;
  font-weight: 400;
}

/* 隐藏数字输入框的上下箭头 */
.quantity-input::-webkit-outer-spin-button,
.quantity-input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

.field-item .field-wrap { 
  flex: 1; 
}

:deep(.van-field) { 
  background: #f9fafb; 
  border-radius: 12px; 
  height: 44px; 
  line-height: 44px; 
}

:deep(.van-field__control) { 
  font-weight: 700; 
  font-size: 16px; 
}

.divider { 
  height: 1px; 
  background: #e2e8f0; 
  margin: 0 4px; 
}

.h50 {
  margin-top: 50px;
}

/* 确认上架按钮样式（与ListingPage.vue保持一致） */
.action-box.h50 {
  background: linear-gradient(135deg, #0dae7a 0%, #0a8f63 100%);
  color: white;
  font-weight: 700;
  letter-spacing: 0.5px;
  box-shadow: 0 8px 32px rgba(13, 174, 122, 0.3);
  border: none;
}

.action-box.h50:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 40px rgba(13, 174, 122, 0.4);
}

.action-box.h50:active {
  transform: translateY(0);
  box-shadow: 0 4px 16px rgba(13, 174, 122, 0.3);
}

/* 日期选择器样式优化 */
:deep(.van-action-sheet) {
  border-radius: 16px 16px 0 0;
}

:deep(.van-action-sheet__header) {
  padding: 20px 16px 16px;
  font-size: 18px;
  font-weight: 600;
  color: #2d3748;
  border-bottom: 1px solid #e2e8f0;
}

:deep(.van-action-sheet__action) {
  padding: 16px;
  font-size: 16px;
  color: #4a5568;
  border-bottom: 1px solid #f7fafc;
  transition: background-color 0.2s ease;
}

:deep(.van-action-sheet__action:active) {
  background-color: #f7fafc;
}

:deep(.van-action-sheet__cancel) {
  margin-top: 8px;
  padding: 16px;
  font-size: 16px;
  color: #718096;
  background-color: #f9fafb;
  border-top: 1px solid #e2e8f0;
}

:deep(.van-action-sheet__cancel:active) {
  background-color: #edf2f7;
}

/* 日期选择项样式 */
.date-selection-item {
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.date-selection-item:hover {
  background-color: #f8fafc;
  border-radius: 8px;
}

.value-with-date {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.value-with-date:hover {
  background-color: #fff3cd;
}

.date-arrow {
  font-size: 12px;
  color: #9ca3af;
  transition: transform 0.2s ease;
}

.value-with-date:hover .date-arrow {
  color: #f8b300;
  transform: translateY(1px);
}

/* 已选择日期的样式 */
.selected-date {
  color: #f8b300 !important;
  font-weight: 600;
}

/* 日期选择按钮的悬停效果 */
.action-box.ghost:hover {
  background-color: #f8fafc;
  transform: translateY(-1px);
  transition: all 0.2s ease;
}
</style>
